<?php
namespace WDB\Query\Element\Datatype;
use WDB,
    WDB\Exception;

/**
 *
 * @author Richard Ejem <richard(at)ejem.cz>
 * @package WDB
 */
abstract class AbstractType extends WDB\BaseObject implements iDatatype
{
    protected $value;
    
    public function equals(iDatatype $to)
    {
        return \get_class($to) === \get_class($this) && $this->value = $to->value;
    }
    
    public function isNull()
    {
        return $this->value === NULL;
    }
    
    public function getValue()
    {
        return $this->value;
    }
    
    public function __toString()
    {
        return (string)$this->getValue();
    }

    public static function createDatatype($value)
    {
        if ($value instanceof iDatatype) return $value;
        if ($value instanceof \DateTime)
        {
            if (isset($value->_wdbType) && $value->_wdbType == 'Date')
            {
                return new Date($value);
            }
            else
            {
                return new DateTime($value);
            }
        }
        if ($value instanceof \DateInterval)
        {
            return new Time($value);
        }
        if (is_array($value))
        {
            return new Set($value);
        }
        switch (gettype($value))
        {
            case 'boolean':
                return new Integer($value ? 1 : 0);
            case 'integer':
                return new Integer($value);
            case 'double':
                return new Float($value);
            case 'string':
                return new String($value);
            case 'NULL':
                return new TNull();
        }
        throw new Exception\WDBException("unknown type: ".gettype($value)." or class: ".get_class($value));
    }
}
